package com.zhan.picturebackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.zhan.picturebackend.annotation.AuthCheck;
import com.zhan.picturebackend.common.BaseResponse;
import com.zhan.picturebackend.common.ResultUtils;
import com.zhan.picturebackend.constant.UserConstant;
import com.zhan.picturebackend.exception.BusinessException;
import com.zhan.picturebackend.exception.ErrorCode;
import com.zhan.picturebackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    /**
     * 测试上传文件
     * @param multipartFile 封装的文件
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        //获取文件名
        String filename = multipartFile.getOriginalFilename();
        //设置文件路径
        String filepath = String.format("/test/%s", filename);
        //创建临时文件
        File file = null;
        try {
            file = File.createTempFile(filepath, null);
            //接收传来的文件
            multipartFile.transferTo(file);
            //上传文件到腾讯云
            cosManager.putObject(filepath, file);
            //返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        } finally {
            //最后一定要删除临时文件
            if (file != null) {
                boolean deleteResult = file.delete();
                if (!deleteResult) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 测试下载文件
     * @param filepath 文件写入到的路径
     * @param response 响应参数
     * @throws IOException
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInputStream = null;
        try {
            //获取文件
            COSObject cosObject = cosManager.getObject(filepath);
            //获取文件流
            cosObjectInputStream = cosObject.getObjectContent();
            //设置响应头
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
            //把文件写入流转成字节数组写入到响应流
            byte[] byteArray = IOUtils.toByteArray(cosObjectInputStream);
            response.getOutputStream().write(byteArray);
            //刷新流,防止缓冲区有数据没写入，导致文件内容不完整
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("file download error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载文件失败");
        } finally {
            //关闭流
            if (cosObjectInputStream != null) {
                cosObjectInputStream.close();
            }
        }
    }
}
